package com.travelcloud.module.product.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import com.travelcloud.framework.utils.MyBeanUtils;
import com.travelcloud.module.product.entity.ProductInfo;
import com.travelcloud.module.product.service.impl.ProductInfoServiceImpl;
import com.travelcloud.module.product.vo.ProductInfoAddVo;
import com.travelcloud.module.product.vo.ProductInfoQueryVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import java.util.List;


/**
 * 产品管理
 *
 * @author Zee
 * @since 2020年6月19日
 */
@RestController
@RequestMapping("mapper/product")
@Api(tags = "产品管理")
public class ProductInfoController {

    @Autowired
    private ProductInfoServiceImpl productInfoService;

    @GetMapping("find-by-id")
    @ApiOperation(value = "通过Id查询产品信息", notes = "通过Id查询产品信息")
    public ProductInfoQueryVo findById(@RequestParam @ApiParam(value = "产品Id", name = "id") Integer id) {
        return MyBeanUtils.copyToBean(productInfoService.getById(id), ProductInfoQueryVo::new);
    }

    @PostMapping("/page")
    @ApiOperation(value = "分页查询产品信息", notes = "通过Id查询产品信息")
    public IPage findPage(@Validated @RequestBody ProductInfoQueryVo productInfoQueryVo) {
        IPage page = new Page(productInfoQueryVo.getPageNum(), productInfoQueryVo.getPageSize());
        // 将vo => po，进行page查询
        QueryWrapper wrapper = new QueryWrapper<>(MyBeanUtils.copyToBean(productInfoQueryVo, ProductInfo::new));

        productInfoService.page(page);
        // page.getRecords()此时为po类型，转换为vo
        page.setRecords(MyBeanUtils.copyToList(page.getRecords(), ProductInfoQueryVo::new
        ));

        return page;
    }

    @GetMapping("/findByLikeName")
    @ApiOperation(value = "通过name模糊查询", notes = "通过name模糊查询")
    public List findByLikeName(@ApiParam(value = "产品名称", name = "productName") @RequestParam String productName) {
        return productInfoService.getByLikeName(productName);
    }

    @PostMapping("/add")
    @ApiOperation(value = "添加产品", notes = "添加产品")
    public void add(@Valid @RequestBody ProductInfoAddVo vo) {
        productInfoService.save(MyBeanUtils.copyToBean(vo, ProductInfo::new));
    }

    @PostMapping("/deleteById")
    public void deleteById(@Valid @NotBlank Integer id) {
        productInfoService.removeById(id);
    }

    @PostMapping("/updateById")
    public void updateById(@Valid ProductInfoAddVo vo) {
        productInfoService.updateById(MyBeanUtils.copyToBean(vo, ProductInfo::new));
    }
}
